import { h, Fragment } from "preact";
import * as React from "preact";
import { Handlers, PageProps } from "$fresh/server.ts";
import { getDbClient, Post } from "../utils/db.ts";
import HeadComponent from "../components/Head.tsx";
import Container from "../components/Container.tsx";
import Card from "../components/Card.tsx";
import Button from "../components/Button.tsx";
import Pagination from "../components/Pagination.tsx";

interface IndexPageData { 
  posts: Post[]; 
  showDeleteSuccessMessage?: boolean; 
  showLoginSuccessMessage?: boolean;
  totalPosts: number;
  currentPage: number;
  totalPages: number;
  searchQuery?: string;
  yearFilter?: string;
  monthFilter?: string;
  availableYears: string[];
  availableMonths: string[];
}

export const handler: Handlers<IndexPageData> = {
  async GET(req, ctx) {
    const url = new URL(req.url);
    const showDeleteSuccessMessage = url.searchParams.get("deleted") === "true";
    const showLoginSuccessMessage = url.searchParams.get("login_success") === "true";
    const page = parseInt(url.searchParams.get("page") || "1");
    const pageSize = 6; // 每页显示6篇文章
    
    // 获取搜索和筛选参数
    const searchQuery = url.searchParams.get("search") || "";
    const yearFilter = url.searchParams.get("year") || "";
    const monthFilter = url.searchParams.get("month") || "";
    
    let whereClause = "";
    const queryParams: any[] = [];
    
    // 构建查询条件
    if (searchQuery) {
      whereClause = "WHERE title LIKE ? OR content LIKE ?";
      queryParams.push(`%${searchQuery}%`, `%${searchQuery}%`);
    }
    
    // 添加日期筛选
    if (yearFilter || monthFilter) {
      whereClause = whereClause ? `${whereClause} AND ` : "WHERE ";
      
      if (yearFilter && monthFilter) {
        whereClause += "YEAR(created_at) = ? AND MONTH(created_at) = ?";
        queryParams.push(yearFilter, monthFilter);
      } else if (yearFilter) {
        whereClause += "YEAR(created_at) = ?";
        queryParams.push(yearFilter);
      } else if (monthFilter) {
        whereClause += "MONTH(created_at) = ?";
        queryParams.push(monthFilter);
      }
    }
    
    const offset = (page - 1) * pageSize;
    
    let client;
    try {
      client = await getDbClient();
      
      // 获取总文章数
      const countQuery = `SELECT COUNT(*) as count FROM posts ${whereClause}`;
      const countResult = await client.query(countQuery, queryParams);
      const totalPosts = (countResult[0] as { count: number }).count;
      const totalPages = Math.ceil(totalPosts / pageSize);
      
      // 分页查询文章
      const postsQuery = `
        SELECT id, title, content, created_at FROM posts 
        ${whereClause}
        ORDER BY created_at DESC LIMIT ? OFFSET ?
      `;
      const results = await client.query(
        postsQuery, 
        [...queryParams, pageSize, offset]
      );
      const posts = results as Post[];
      
      // 获取数据库中的年份列表
      const yearsQuery = `
        SELECT DISTINCT YEAR(created_at) as year 
        FROM posts 
        ORDER BY year DESC
      `;
      const yearsResult = await client.query(yearsQuery);
      const availableYears = yearsResult.map((row: any) => row.year);
      
      // 获取数据库中的月份列表
      const monthsQuery = `
        SELECT DISTINCT MONTH(created_at) as month 
        FROM posts 
        ORDER BY month ASC
      `;
      const monthsResult = await client.query(monthsQuery);
      const availableMonths = monthsResult.map((row: any) => row.month);
      
      return ctx.render({ 
        posts, 
        showDeleteSuccessMessage, 
        showLoginSuccessMessage,
        totalPosts,
        currentPage: page,
        totalPages,
        searchQuery,
        yearFilter,
        monthFilter,
        availableYears,
        availableMonths
      });
    } catch (error) {
      console.error("Error fetching posts:", error);
      return ctx.render({ 
        posts: [], 
        showDeleteSuccessMessage: false, 
        showLoginSuccessMessage: false,
        totalPosts: 0,
        currentPage: 1,
        totalPages: 0,
        searchQuery: "",
        yearFilter: "",
        monthFilter: "",
        availableYears: [],
        availableMonths: []
      });
    } finally { 
      if (client) await client.close(); 
    }
  },
};

export default function HomePage({ data, state }: PageProps<IndexPageData>) {
  const { 
    posts, 
    showDeleteSuccessMessage, 
    showLoginSuccessMessage, 
    currentPage, 
    totalPages, 
    searchQuery, 
    yearFilter, 
    monthFilter,
    availableYears = [],
    availableMonths = []
  } = data;
  const isAdmin = state.isAdmin as boolean || false;

  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    return date.toLocaleDateString('zh-CN', { 
      year: 'numeric',
      month: '2-digit', 
      day: '2-digit'
    });
  };
  
  // 生成随机动画延迟以创造错落有致的效果
  const randomDelay = () => {
    return (Math.random() * 0.7).toFixed(2);
  };

  // 获取月份名称
  const getMonthName = (monthNum: string | number) => {
    // 将月份转为字符串
    const monthStr = String(monthNum);
    
    const monthNames: Record<string, string> = {
      "1": "1月", "01": "1月",
      "2": "2月", "02": "2月",
      "3": "3月", "03": "3月",
      "4": "4月", "04": "4月",
      "5": "5月", "05": "5月",
      "6": "6月", "06": "6月",
      "7": "7月", "07": "7月",
      "8": "8月", "08": "8月",
      "9": "9月", "09": "9月",
      "10": "10月",
      "11": "11月",
      "12": "12月"
    };
    
    return monthNames[monthStr] || `${monthStr}月`;
  };

  return (
    <>
      <HeadComponent title="MiniBlog" description="MiniBlog">
        <link rel="stylesheet" href="/styles.css" />
        <script src="/scripts.js"></script>
        <script dangerouslySetInnerHTML={{__html: `
          // 仅在首页添加禁止滚动的类
          document.addEventListener('DOMContentLoaded', function() {
            // 确保是首页
            if (window.location.pathname === '/' || window.location.pathname === '') {
              document.body.classList.add('body-fullscreen-no-scroll');
            }
            
            // 设置管理员状态
            document.body.setAttribute('data-is-admin', '${isAdmin}');
          });
        `}} />
      </HeadComponent>
      
      {/* Butterfly Animation Container - z-index 10 */}
      <div id="butterfly-sanctuary" class="fixed top-0 left-0 w-1/4 h-full pointer-events-none z-[10] opacity-80"></div>

      {/* Sun Animation Container - z-index 10 */}
      <a href="/admin/login" id="admin-sun-link" aria-label="Admin Login" class="fixed top-5 right-5 w-[250px] h-[250px] z-[10] pointer-events-auto block group">
        <div id="sun-rays-container" class="w-full h-full pointer-events-none group-hover:opacity-80 transition-opacity duration-300"></div>
      </a>
      
      {/* 顶部导航栏 - Frosted Glass Effect - z-index 50 (highest) */}
      <div class="sticky top-0 z-50 bg-neutral-50/80 backdrop-blur-lg shadow-sm nav-container">
        <div class="container mx-auto px-4 py-3 flex items-center justify-between">
          <a href="/" class="flex items-center gap-2 group miniblock-title-container">
            {/* MiniBlog Icon with new color */}
            <div class="h-7 w-7 flex items-center justify-center rounded-md bg-[#7b5e4d] text-white font-medium text-sm group-hover:bg-[#6a5040] transition-colors duration-200">
              m
            </div>
            {/* MiniBlog Text with new color */}
            <span class="text-xl font-semibold text-[#7b5e4d] group-hover:text-[#6a5040] transition-colors duration-200">MiniBlog</span>
          </a>
          
          <div class="flex items-center gap-4">
            {/* 搜索框放在顶部导航 */}
            <div class="w-64">
              <form method="GET" action="/" class="flex">
                <div class="relative flex-grow">
                  <input 
                    type="text" 
                    name="search" 
                    placeholder="搜索文章..." 
                    value={searchQuery}
                    class="w-full py-2 pl-8 pr-8 text-sm bg-slate-100/70 border border-slate-300/70 rounded-lg focus:border-amber-500 focus:ring-2 focus:ring-amber-500/30 focus:bg-white transition-all duration-200 placeholder-slate-400 text-slate-700" 
                  />
                  <div class="absolute inset-y-0 left-2.5 flex items-center pointer-events-none text-slate-400">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                      <path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                    </svg>
                  </div>
                  {searchQuery && (
                    <a 
                      href="/"
                      class="absolute inset-y-0 right-2.5 flex items-center text-slate-400 hover:text-amber-600 transition-colors duration-200 p-1 rounded-full hover:bg-slate-200/80"
                      aria-label="清除搜索"
                    >
                      <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                      </svg>
                    </a>
                  )}
                </div>
              </form>
            </div>
            {/* Admin button remains here if needed */}
            {isAdmin && (
              <div>
                <Button href="/new" variant="primary" size="sm" className="bg-[#7b5e4d] hover:bg-[#6a5040] text-white">
                  创建文章
                </Button>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 主要内容区域 - z-index 20 (above background animations) */}
      <div 
        id="content-area" 
        class="relative mx-auto max-w-screen-lg px-4 py-2 sm:px-6 lg:px-8 bg-transparent z-[20] overflow-hidden"
      >
        {/* 消息通知 */}
        <Container>
          {showLoginSuccessMessage && (
            <div class="mb-6 px-6 py-3 bg-green-50 text-green-700 text-sm rounded-lg border border-green-200">
              登录成功！欢迎回来。
            </div>
          )}
          
          {showDeleteSuccessMessage && (
            <div class="mb-6 px-6 py-3 bg-red-50 text-red-700 text-sm rounded-lg border border-red-200">
              文章已成功删除。
            </div>
          )}
        </Container>

        {/* 日期筛选区域 - Reverted Position */}
        <Container>
          <div class="flex justify-end items-center border-gray-100 pb-4 mb-8">
            <form method="GET" action="/" class="flex items-center gap-3" id="filterForm">
              <input type="hidden" name="search" value={searchQuery || ''} />
              <select 
                name="year" 
                onchange="this.form.submit()"
                class="px-3 py-2 text-sm bg-slate-100/70 border border-slate-300/70 rounded-lg focus:border-amber-500 focus:ring-2 focus:ring-amber-500/30 focus:bg-white transition-all duration-200 text-slate-700 appearance-none text-center styled-select"
              >
                <option value="">全部年份</option>
                {availableYears.map(year => (
                  <option value={year} selected={yearFilter === year}>{year}年</option>
                ))}
              </select>
              <select 
                name="month" 
                onchange="this.form.submit()"
                class="px-3 py-2 text-sm bg-slate-100/70 border border-slate-300/70 rounded-lg focus:border-amber-500 focus:ring-2 focus:ring-amber-500/30 focus:bg-white transition-all duration-200 text-slate-700 appearance-none text-center styled-select"
              >
                <option value="">全部月份</option>
                {availableMonths.map(month => (
                  <option value={month} selected={monthFilter === month}>{getMonthName(month)}</option>
                ))}
              </select>
              {(yearFilter || monthFilter) && (
                <a 
                  href={searchQuery ? `/?search=${encodeURIComponent(searchQuery)}` : "/"}
                  class="ml-2 px-3 py-1.5 text-xs bg-slate-200 text-slate-600 rounded-lg hover:bg-slate-300 transition-all"
                >
                  重置筛选
                </a>
              )}
            </form>
          </div>
        </Container>

        {/* 文章列表 */}
        <Container size="lg">
          {/* 空状态 */}
          {posts.length === 0 ? (
            <div class="py-16 text-center">
              <div class="text-5xl mb-6 text-gray-300 mx-auto">✒️</div>
              <h2 class="text-xl font-medium text-gray-700 mb-3">暂无文章</h2>
              <p class="text-gray-500 mb-6 max-w-md mx-auto">
                {searchQuery || yearFilter || monthFilter 
                  ? "没有找到符合条件的文章，请尝试调整筛选条件。" 
                  : isAdmin ? "创建您的第一篇文章，开始分享您的想法。" : "内容正在精心创作中，敬请期待..."}
              </p>
              {isAdmin && (
                <Button href="/new" variant="primary" size="md">
                  写文章
                </Button>
              )}
            </div>
          ) : (
            <>
              <div class="grid grid-cols-1 gap-3 max-w-4xl mx-auto">
                {posts.map((post, index) => {
                  // 计算颜色索引(1-5)
                  const colorIndex = (index % 5) + 1;
                  // 根据colorIndex选择颜色
                  let titleColor;
                  switch(colorIndex) {
                    case 1: titleColor = "rgba(245, 158, 11, 0.85)"; break; // Amber
                    case 2: titleColor = "rgba(16, 185, 129, 0.85)"; break;  // Emerald
                    case 3: titleColor = "rgba(124, 58, 237, 0.85)"; break;  // Purple
                    case 4: titleColor = "rgba(239, 68, 68, 0.85)"; break;   // Red
                    case 5: titleColor = "rgba(59, 130, 246, 0.85)"; break;  // Blue
                    default: titleColor = "rgba(75, 85, 99, 0.85)"; // 默认灰色
                  }
                  
                  return (
                    <article 
                      key={post.id} 
                      class="relative z-10 animate-fade-up glass-card glow-border rounded-lg overflow-hidden"
                      style={{animationDelay: `${index * 0.05}s`}}
                    >
                      <div class="p-5">
                        <div class="flex justify-between items-start mb-2">
                          {/* 使用内联样式设置标题颜色，匹配悬浮边框颜色 */}
                          <h2 class="text-xl font-medium">
                            <a href={`/posts/${post.id}`} style={{color: titleColor, fontWeight: 500}}>{post.title}</a>
                          </h2>
                          <time class="text-xs text-gray-500 flex-shrink-0 ml-2">
                            {formatDate(post.created_at)}
                          </time>
                        </div>
                        
                        <p class="text-gray-500 text-sm line-clamp-1 mb-4">
                          {post.content.replace(/<\/?[^>]+(>|$)/g, "")}
                        </p>
                        
                        <div class="flex justify-between items-center">
                          {/* Gold Read More Link */}
                          <a 
                            href={`/posts/${post.id}`} 
                            class="inline-flex items-center text-amber-600 hover:text-amber-700 text-xs font-medium"
                          >
                            阅读全文
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3 ml-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3" />
                            </svg>
                          </a>
                          
                          {isAdmin && (
                            <div class="flex gap-2">
                              <Button
                                href={`/admin/posts/${post.id}/edit`}
                                variant="ghost"
                                size="sm"
                                className="text-[#5a3e2e] font-medium hover:text-[#7b5e4d] hover:bg-[#7b5e4d]/10 border border-gray-200 hover:border-[#7b5e4d]"
                              >
                                编辑
                              </Button>
                              <form 
                                method="POST" 
                                action="/api/posts/delete" 
                                onSubmit={(e) => { if (!confirm('确定要删除这篇文章吗？')) e.preventDefault(); }}
                                class="inline"
                              >
                                <input type="hidden" name="post_id" value={post.id} />
                                <Button
                                  type="submit"
                                  variant="ghost"
                                  size="sm"
                                  className="text-red-600 font-medium hover:text-red-700 hover:bg-red-50 border border-gray-200 hover:border-red-300"
                                >
                                  删除
                                </Button>
                              </form>
                            </div>
                          )}
                        </div>
                      </div>
                    </article>
                  );
                })}
              </div>
              <Pagination 
                currentPage={currentPage}
                totalPages={totalPages}
                searchQuery={searchQuery}
                yearFilter={yearFilter}
                monthFilter={monthFilter}
              />
            </>
          )}
        </Container>
      </div>
    </>
  );
}